<template>
    <div class="grade-result">
        <Card>
            <Collapse v-model="openPanel">
                <Panel name="1">
                    基本信息
                    <div class="content" slot="content">
                        <Form ref="formData" :model="formData" :label-width="150" disabled>
                            <Row>
                                <Col :lg="24" :xl="12">
                                    <FormItem label="评级模型" prop="elementNo">
                                        <Select v-model="formData.modelCode" @on-change="change" placeholder
                                                style="width:200px;">
                                            <Option
                                                v-for="(item,index) in dataList"
                                                v-show="index>= pageData.begin && index < pageData.end"
                                                :key="index"
                                                :value="item.modelCode"
                                            >{{ item.modelName }}
                                            </Option>
                                        </Select>
                                    </FormItem>
                                </Col>
                                <Col :lg="24" :xl="12">
                                    <FormItem label="合作商名称">
                                        <Input :value="pageParams.channelFullName" placeholder style="width:200px"/>
                                    </FormItem>
                                </Col>
                            </Row>
                        </Form>
                        <Form ref="resultFormData" :model="resultFormData" :label-width="150">
                            <template v-for="(item,index) in resultForm">
                                <ResultItem
                                    :form="item"
                                    :key="index"
                                    :formData="resultFormData"
                                    :dataDict="dataDict"
                                    :pageParams="pageParams"/>
                            </template>
                        </Form>
                    </div>
                </Panel>
                <Panel name="2">
                    评分结果
                    <div class="content" slot="content">
                        <Form ref="result" :model="result" :label-width="150" :disabled="true">
                            <FormItem label="模型得分">
                                <Input clearable :value="totalScore" placeholder
                                       style="width:200px"/>
                            </FormItem>
                        </Form>
                    </div>
                </Panel>
            </Collapse>
            <div class="back text-center">
                <Button type="primary" @click="submit">保存</Button>
            </div>
            <Spin size="large" fix v-if="spinShow"></Spin>
        </Card>
    </div>
</template>

<script>
import {getDictDataList, add} from "_p/afs-channel/assets/js/utils";
import {queryGradeModel, getByModelCode, saveChangeResult} from "_p/afs-channel/api/grade-model"

import ResultItem from "../../components/result-item-change"
import {deepClone} from "@/libs/utils/ObjectClone";

export default {
    // 评级页面
    name: 'GradeResult',
    components: {ResultItem},
    data() {
        return {
            spinShow: false,
            pageData: {},
            dataList: [],
            result: {},
            openPanel: [1, 2],
            formData: {}, //评级模型 选择
            dataDict: {},
            resultFormData: {}, // 模型数据form
            resultForm: [],
            totalScore: 0,// 总分
            pageParams: null,
        }
    },
    watch: {
        resultFormData: {
            handler(val, oldVal) {
                console.log(val, '----', oldVal)
                this.onResultFormChange(val)
            },
            deep: true
        }
    },
    computed: {
        // modelSocre() {
        //     let score = 0;
        //     for (let key in this.resultFormData) {
        //         let index = this.resultForm.findIndex(e => e.elementCode === key)
        //         if (this.resultFormData[key] && index >= 0)
        //             score += this.resultFormData[key]
        //     }
        //     return score
        // }
    },
    created() {
        this.getParams();
    },
    mounted() {
        this.init();
    },
    methods: {
        init() {
            let params = {
                pageNumber: 1,
                pageSize: 10
            }
            this.queryData(params)
            this.change(this.pageParams.modelCode)

        },
        // 获取初始数据
        getParams() {
            const pageParams = this.afs.getPageParams(this);
            const {modelCode} = pageParams
            this.formData.modelCode = modelCode
            this.pageParams = pageParams;
            console.log(pageParams, 'pageParams')
        },
        getDictDataList(dictArr) {
            getDictDataList(dictArr).then(res => {
                console.group("数据字典:");
                console.log(dictArr.join("  "));
                console.log(JSON.parse(JSON.stringify(res)));
                console.groupEnd();
                this.dataDict = res;
                this.spinShow = false;
            }).catch(e => {
                console.error(e)
                this.spinShow = false;
            });
        },
        queryData(queryData) {
            if (!queryData) return;
            queryGradeModel(queryData).then((res) => {
                if (res.code === "0000" && res.data) {
                    let {records, total} = res.data;
                    if (records && records.length > 0) {
                        this.pageData = {
                            total: total,
                            begin: 0,
                            end: 10
                        }
                        this.dataList = records
                    }
                }
            })
        },

        change(val) {
            this.spinShow = true;
            getByModelCode(val).then(res => {
                if (res.code === "0000" && res.data) {
                    this.sortData(res.data);
                }
            }).catch(e => {
                console.error(e)
                this.spinShow = false;
            })
        },
        sortData(data) {
            if (Array.isArray(data) && data.length <= 0) return;
            // 一二级分类 特别注意 数据返回格式
            let firstLevel = this.getLevelData(data, '1'),
                secondLevel = this.getLevelData(data, '2'),
                resultForm = [],
                dictArr = new Set(['channelGradeElement', 'channelGradeLevel1Element']), // 渠道评级一级指标(channelGradeLevel1Element)
                resultFormData = {};

            console.log('firstLevel', firstLevel);
            // console.log('secondLevel', secondLevel);
            firstLevel.forEach(ele => {
                const {attributes, id, state, text} = ele;
                let item = {id, state, text, children: []}
                let {elementCode} = attributes;
                let obj = {
                    [elementCode]: this.pageParams[elementCode],
                    [elementCode + '_addScore']: this.pageParams[elementCode + '_addScore'],
                }
                resultForm.push(Object.assign({}, item, attributes, obj))
                resultFormData[attributes.elementCode + '_addScore'] = this.pageParams[attributes.elementCode + '_addScore']
            });
            secondLevel.forEach(ele => {
                const {attributes, id, state, text, pid} = ele;
                let item = {id, state, text, pid},
                    index = resultForm.findIndex(e => e.elementNo === attributes.upElementNo),
                    {elementCode} = attributes,
                    obj = {
                        elementStr: this.pageParams[elementCode],
                        elementValue: this.pageParams[elementCode + 'Value'],
                        [elementCode]: this.pageParams[elementCode],
                        [elementCode + 'Value']: this.pageParams[elementCode + 'Value'],
                    };
                //
                if (attributes.elementEditType === "0") {
                    dictArr.add(attributes.elementEditSrc)
                }
                if (attributes.dscode === "1") {
                    resultFormData[attributes.elementCode] = Number(this.pageParams[attributes.elementCode]) || 0
                }

                if (index >= 0)
                    resultForm[index].children.push(Object.assign({}, item, attributes, obj))
            })
            console.log(resultForm, 'resultForm')
            console.log(resultFormData, 'resultFormData')
            this.resultFormData = resultFormData

            this.resultForm = resultForm;
            // dictArr.add('channelGradeElement') // elementName
            this.getDictDataList([...dictArr]);
        },
        getLevelData(data, level) {
            if (!data || !level) return;
            return data.filter(e => e.attributes && e.attributes.elementType === level).sort((a, b) => a.attributes.seqno - b.attributes.seqno)
        },
        submit() {
            console.log(this.resultFormData);
            this.$refs.resultFormData.validate(valid => {
                console.log(valid, 'valid');
                if (valid) {
                    this.submitQuery()
                }
            })
        },
        submitQuery() {
            this.spinShow = true;
            const {resultId, modelCode} = this.pageParams
            let data = {
                modelCode,
                modelScore: this.totalScore,
                resultId,
                dtoList: []
            };

            this.resultForm.forEach(item => {
                let obj = {
                    subId: this.pageParams[item.elementCode + '_subId'],
                    score: item[item.elementCode],
                    addScore: this.resultFormData[item.elementCode + '_addScore'],
                    level2Elements: []
                }
                item.children.forEach(itm => {
                    if (itm.dscode === "1") {
                        obj.level2Elements.push({
                            elementNo: itm.elementNo,
                            elementStr: this.resultFormData[itm.elementCode],
                            elementValue: itm.elementValue
                        })
                    }
                })
                if (obj.subId)
                    data.dtoList.push(obj);
            })
            console.log(JSON.stringify(data), 'data')
            saveChangeResult(data).then(res => {
                this.spinShow = false;
                if (res.code === "0000" && res.data) {
                    this.$Message.success(res.data)
                    this.afs.closeTab(this);
                }
            }).catch(e => {
                this.spinShow = false;
                console.error(e);
            })
        },
        getValue(value, dict) {
            if (!value || !dict) return;
            for (let i = 0; i < dict.length; i++) {
                if (value === dict[i].value)
                    return dict[i].title
            }
            return '';
        },
        onResultFormChange(val) {
            let resultForm = deepClone(this.resultForm)
            let totalScore = 0;
            resultForm.forEach(item => {
                let itemScore = 0;
                item.children.forEach(itm => {
                    if (itm.dscode === "1" && val[itm.elementCode] !== undefined) {
                        itm.elementValue = val[itm.elementCode] * itm.elementWeight / 100
                    }
                    if (isNaN(itm.elementValue))
                        itm.elementValue = 0;
                    itemScore = add(itemScore, itm.elementValue)
                })
                if (val[item.elementCode + '_addScore'] !== undefined) {
                    totalScore = add(totalScore, val[item.elementCode + '_addScore'])
                }
                if (isNaN(itemScore))
                    itm.itemScore = 0;
                item[item.elementCode] = itemScore
                totalScore = add(itemScore, totalScore)
            })
            this.resultForm = resultForm
            this.totalScore = totalScore
        },
    }
}
</script>

<style lang="less">
@import "../../../../assets/css/channelBase.css";

。grade-result {
    position: relative;
}

.back {
    padding-top: 16px;
}

.text-center {
    text-align: center;

    button:not(:last-child) {
        margin-right: 16px;
    }
}
</style>
